package fina2.dcs.sys.validator;

import java.io.Serializable;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.log.Logging;

@Name("propValidator")
@Scope(ScopeType.SESSION)
public class PropertyValidator implements Serializable {

	private String value;
	private ResourceBundle bundle = null;

	private Log log = Logging.getLog(getClass());

	public PropertyValidator() {
		try {
			UIViewRoot ui = FacesContext.getCurrentInstance().getViewRoot();
			Locale l = ui.getLocale();
			ClassLoader cl = Thread.currentThread().getContextClassLoader();
			bundle = ResourceBundle.getBundle("messages", l, cl);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
	}

	public void validateValue(FacesContext fc, UIComponent ui, Object value) throws ValidatorException {
		
		this.value = value.toString();
		if (this.value.trim().length() < 1) {
			FacesMessage fm = new FacesMessage();
			fm.setSeverity(FacesMessage.SEVERITY_ERROR);
			fm.setDetail("Value is required!");
			throw new ValidatorException(fm);
		}
	}
	public void validateMaxFilesValue(FacesContext fc, UIComponent ui, Object value) throws ValidatorException {
		this.value = value.toString();
		if (this.value.trim().length() < 1) {
			FacesMessage fm = new FacesMessage();
			fm.setSeverity(FacesMessage.SEVERITY_ERROR);
			fm.setDetail("Value is required!");
			throw new ValidatorException(fm);
		}
		
		try{
			Double.parseDouble(this.value);	
		}
		catch(NumberFormatException ex){
			FacesMessage fm = new FacesMessage();
			fm.setSeverity(FacesMessage.SEVERITY_ERROR);
			fm.setDetail("Invalid Number!");
			throw new ValidatorException(fm);
		}
			
		
	}
	public void validateConfirmValue(FacesContext fc, UIComponent ui, Object confValue) throws ValidatorException {
		String confirmVal = confValue.toString();
		if (confirmVal.trim().length() < 1) {
			FacesMessage fm = new FacesMessage();
			fm.setSeverity(FacesMessage.SEVERITY_ERROR);
			fm.setDetail("Value is required!");
			throw new ValidatorException(fm);
		} else if (!confirmVal.trim().equals(value.trim())) {
			FacesMessage fm = new FacesMessage();
			fm.setSeverity(FacesMessage.SEVERITY_ERROR);
			fm.setDetail("Confirmation error!");
			throw new ValidatorException(fm);
		}
	}
}
